package com.campsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campsys.entity.User;
import com.campsys.mapper.UserMapper;
import com.campsys.service.AdminStudentService;
import com.campsys.service.dto.StudentDTO;
import com.campsys.service.dto.StudentQueryDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AdminStudentServiceImpl implements AdminStudentService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public IPage<User> getStudentList(Page<User> page, StudentQueryDTO queryDTO) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRoleType, 3);  // 3-学生角色
        
        // 添加查询条件
        if (StringUtils.isNotBlank(queryDTO.getUsername())) {
            wrapper.like(User::getUsername, queryDTO.getUsername());
        }
        if (StringUtils.isNotBlank(queryDTO.getRealName())) {
            wrapper.like(User::getRealName, queryDTO.getRealName());
        }
        if (StringUtils.isNotBlank(queryDTO.getPhone())) {
            wrapper.like(User::getPhone, queryDTO.getPhone());
        }
        if (queryDTO.getStatus() != null) {
            wrapper.eq(User::getStatus, queryDTO.getStatus());
        }
        
        wrapper.orderByDesc(User::getCreateTime);
        return userMapper.selectPage(page, wrapper);
    }
    
    @Override
    @Transactional
    public void addStudent(StudentDTO studentDTO) {
        // 验证必填字段
        if (StringUtils.isBlank(studentDTO.getPassword())) {
            throw new IllegalArgumentException("密码不能为空");
        }
        
        // 验证用户名是否已存在
        if (isUsernameExists(studentDTO.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        
        // 验证手机号是否已存在
        if (isPhoneExists(studentDTO.getPhone())) {
            throw new IllegalArgumentException("手机号已存在");
        }
        
        // 创建用户对象
        User user = new User();
        BeanUtils.copyProperties(studentDTO, user);
        user.setRoleType(3);  // 3-学生角色
        user.setStatus(0);  // 0-待审核
        user.setCreateTime(LocalDateTime.now());
        
        userMapper.insert(user);
    }
    
    @Override
    @Transactional
    public void updateStudent(StudentDTO studentDTO) {
        // 验证用户是否存在
        User existingUser = userMapper.selectById(studentDTO.getId());
        if (existingUser == null || existingUser.getRoleType() != 3) {
            throw new IllegalArgumentException("学生不存在");
        }
        
        // 验证用户名是否已被其他用户使用
        if (!StringUtils.equals(existingUser.getUsername(), studentDTO.getUsername())) {
            LambdaQueryWrapper<User> usernameWrapper = new LambdaQueryWrapper<>();
            usernameWrapper.eq(User::getUsername, studentDTO.getUsername());
            if (userMapper.selectCount(usernameWrapper) > 0) {
                throw new IllegalArgumentException("用户名已存在");
            }
        }
        
        // 验证手机号是否已被其他用户使用
        if (!StringUtils.equals(existingUser.getPhone(), studentDTO.getPhone())) {
            LambdaQueryWrapper<User> phoneWrapper = new LambdaQueryWrapper<>();
            phoneWrapper.eq(User::getPhone, studentDTO.getPhone());
            if (userMapper.selectCount(phoneWrapper) > 0) {
                throw new IllegalArgumentException("手机号已存在");
            }
        }
        
        // 更新用户信息
        User user = new User();
        BeanUtils.copyProperties(studentDTO, user);
        user.setRoleType(3);  // 确保角色类型不变
        user.setUpdateTime(LocalDateTime.now());
        
        // 如果密码为空，保持原密码不变
        if (StringUtils.isBlank(studentDTO.getPassword())) {
            user.setPassword(existingUser.getPassword());
        }
        
        userMapper.updateById(user);
    }
    
    @Override
    @Transactional
    public void deleteStudent(Long id) {
        // 验证用户是否存在
        User user = userMapper.selectById(id);
        if (user == null || user.getRoleType() != 3) {
            throw new IllegalArgumentException("学生不存在");
        }
        
        // TODO: 检查是否有关联的班级或课程
        
        userMapper.deleteById(id);
    }
    
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        if (status != 0 && status != 1) {
            throw new IllegalArgumentException("无效的状态值");
        }
        
        // 验证用户是否存在
        User user = userMapper.selectById(id);
        if (user == null || user.getRoleType() != 3) {
            throw new IllegalArgumentException("学生不存在");
        }
        
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setStatus(status);
        updateUser.setUpdateTime(LocalDateTime.now());
        
        userMapper.updateById(updateUser);
    }
    
    @Override
    public List<StudentDTO> importStudents(MultipartFile file) {
        List<StudentDTO> students = new ArrayList<>();
        
        try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            
            // 从第二行开始读取（第一行是表头）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                
                StudentDTO student = new StudentDTO();
                student.setUsername(getCellValue(row.getCell(0)));
                student.setPassword(getCellValue(row.getCell(1)));
                student.setRealName(getCellValue(row.getCell(2)));
                student.setPhone(getCellValue(row.getCell(3)));
                student.setEmail(getCellValue(row.getCell(4)));
                
                students.add(student);
            }
        } catch (IOException e) {
            log.error("读取Excel文件失败", e);
            throw new IllegalArgumentException("Excel文件格式错误");
        }
        
        return students;
    }
    
    @Override
    @Transactional
    public void auditStudents(List<Long> studentIds) {
        if (studentIds == null || studentIds.isEmpty()) {
            return;
        }
        
        // 批量更新学生状态为已审核
        User updateUser = new User();
        updateUser.setStatus(1);  // 1-已审核
        updateUser.setUpdateTime(LocalDateTime.now());
        
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(User::getId, studentIds)
              .eq(User::getRoleType, 3)  // 3-学生角色
              .eq(User::getStatus, 0);  // 0-待审核
        
        userMapper.update(updateUser, wrapper);
    }
    
    private boolean isUsernameExists(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectCount(wrapper) > 0;
    }
    
    private boolean isPhoneExists(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        return userMapper.selectCount(wrapper) > 0;
    }
    
    private String getCellValue(Cell cell) {
        if (cell == null) return "";
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf((long)cell.getNumericCellValue());
            default:
                return "";
        }
    }
} 